#include <iostream>
using namespace std;

// 赋值运算符重载

class Person
{
// friend ostream &operator<<(ostream &cout, MyInteger myint);
public:
    Person (int age)
    {
        m_Age = new int(age);
    }
    ~Person(){
        if (m_Age != NULL)
        {
            delete m_Age;
            m_Age = NULL;
        }
    }
    // 2.重载赋值运算符，只可作为成员函数！
    Person& operator=(Person &p)
    {
        // 编译器默认提供了浅拷贝
        // m_Age = p.m_Age

        // 应该先判断是否有属性在堆区，如果有先释放干净，然后再深拷贝
        if (m_Age != NULL)
        {
            delete m_Age;
            m_Age = NULL;
        }
        // 深拷贝
        m_Age = new int (*p.m_Age);

        return *this;
    } 
// private:
    int *m_Age;
};


void test01() 
{
    Person p1(18);
    Person p2(20);
    cout << "p1 的年龄为：" << *p1.m_Age << endl;
    cout << "p2 的年龄为：" << *p2.m_Age << endl;
    // 堆区内存重复释放，程序崩溃
    // 解决方案：
        //   利用深拷贝解决浅拷贝带来的问题
    p2 = p1;
    cout << "p1 的年龄为：" << *p1.m_Age << endl;
    cout << "p2 的年龄为：" << *p2.m_Age << endl;

    Person p3(30);
    cout << "p3 的年龄为：" << *p3.m_Age << endl;
    p3 = p2 = p1;
    cout << "p1 的年龄为：" << *p1.m_Age << endl;
    cout << "p2 的年龄为：" << *p2.m_Age << endl;
    cout << "p3 的年龄为：" << *p3.m_Age << endl;
} 
 
void test02() 
{

} 

int main()
{
    test01();
    // test02();
    // int a = 0;
    // cout << ++a << endl;
    cout << "hello" << endl;
    return 0;
}